import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'xh_danmu_controller.dart';
import 'xh_danmu_models.dart';

/// 弹幕轨道边界线组件（调试用）
class XhDanmuTrackBorders extends StatelessWidget {
  final XhDanmuController controller;
  final Color borderColor;
  final double borderWidth;
  final bool showLabels;

  const XhDanmuTrackBorders({
    super.key,
    required this.controller,
    this.borderColor = const Color(0x4DFFFFFF),
    this.borderWidth = 1.0,
    this.showLabels = true,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: controller.tracks.map((track) {
        return Positioned(
          top: track.topOffset,
          left: 0,
          right: 0,
          child: Container(
            height: track.height,
            decoration: BoxDecoration(
              border: Border.all(
                color: borderColor,
                width: borderWidth,
              ),
            ),
            child: showLabels
                ? Center(
                    child: Text(
                      '轨道${track.trackId}',
                      style: const TextStyle(
                        color: Colors.white54,
                        fontSize: 12,
                      ),
                    ),
                  )
                : null,
          ),
        );
      }).toList(),
    );
  }
}

/// 弹幕实时调试信息组件
class XhDanmuDebugInfo extends StatelessWidget {
  final XhDanmuController controller;
  final Color backgroundColor;
  final BorderRadius borderRadius;

  const XhDanmuDebugInfo({
    super.key,
    required this.controller,
    this.backgroundColor = const Color(0xDD000000),
    this.borderRadius = const BorderRadius.all(Radius.circular(8)),
  });

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: 10,
      right: 10,
      child: GetBuilder<XhDanmuController>(
        init: controller,
        builder: (ctrl) {
          final status = ctrl.getStatus();

          return Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: backgroundColor,
              borderRadius: borderRadius,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  '时间: ${status.currentTime.toStringAsFixed(1)}s',
                  style: const TextStyle(color: Colors.white, fontSize: 11),
                ),
                Text(
                  '活跃: ${status.totalActiveDanmu}条',
                  style: const TextStyle(color: Colors.green, fontSize: 11),
                ),
                Text(
                  '队列: ${status.totalQueuedDanmu}条',
                  style: const TextStyle(color: Colors.orange, fontSize: 11),
                ),
                Text(
                  '容器: ${status.containerWidth.toStringAsFixed(0)}px',
                  style: const TextStyle(color: Colors.blue, fontSize: 11),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

/// 详细的弹幕状态显示组件
class XhDanmuDetailedStatus extends StatelessWidget {
  final XhDanmuController controller;
  final Color? backgroundColor;
  final BorderRadius? borderRadius;
  final bool showTrackDetails;

  const XhDanmuDetailedStatus({
    super.key,
    required this.controller,
    this.backgroundColor,
    this.borderRadius,
    this.showTrackDetails = true,
  });

  @override
  Widget build(BuildContext context) {
    return GetBuilder<XhDanmuController>(
      init: controller,
      builder: (ctrl) {
        final status = ctrl.getStatus();

        return Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: backgroundColor ?? Colors.black.withOpacity(0.9),
            borderRadius: borderRadius ?? BorderRadius.circular(12),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                'XH弹幕系统状态',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 12),

              // 总体状态
              _buildStatusRow(
                  '播放状态', status.isPlaying ? '播放中' : '暂停', status.isPlaying ? Colors.green : Colors.orange),
              _buildStatusRow('当前时间', '${status.currentTime.toStringAsFixed(1)}s', Colors.blue),
              _buildStatusRow('容器宽度', '${status.containerWidth.toStringAsFixed(0)}px', Colors.blue),
              _buildStatusRow('活跃弹幕', '${status.totalActiveDanmu}条', Colors.green),
              _buildStatusRow('队列弹幕', '${status.totalQueuedDanmu}条', Colors.orange),

              // 轨道详情
              if (showTrackDetails) ...[
                const SizedBox(height: 8),
                const Divider(color: Colors.white30),
                const SizedBox(height: 8),
                const Text(
                  '轨道状态',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 8),
                ...status.trackInfos.map((trackInfo) => Container(
                      margin: const EdgeInsets.only(bottom: 4),
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: _getTrackStatusColor(trackInfo.status).withOpacity(0.2),
                        borderRadius: BorderRadius.circular(4),
                        border: Border.all(
                          color: _getTrackStatusColor(trackInfo.status),
                          width: 1,
                        ),
                      ),
                      child: Row(
                        children: [
                          Text(
                            '轨道${trackInfo.trackId}',
                            style: const TextStyle(color: Colors.white, fontSize: 12),
                          ),
                          const Spacer(),
                          Text(
                            '活跃:${trackInfo.activeDanmuCount}',
                            style: const TextStyle(color: Colors.white70, fontSize: 10),
                          ),
                          const SizedBox(width: 8),
                          Text(
                            '队列:${trackInfo.queuedDanmuCount}',
                            style: const TextStyle(color: Colors.white70, fontSize: 10),
                          ),
                          const SizedBox(width: 8),
                          Text(
                            '负载:${trackInfo.loadScore.toStringAsFixed(1)}',
                            style: const TextStyle(color: Colors.white60, fontSize: 10),
                          ),
                        ],
                      ),
                    )),
              ],
            ],
          ),
        );
      },
    );
  }

  /// 构建状态行
  Widget _buildStatusRow(String label, String value, Color valueColor) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        children: [
          Text(
            '$label: ',
            style: const TextStyle(color: Colors.white70, fontSize: 12),
          ),
          Text(
            value,
            style: TextStyle(
              color: valueColor,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  /// 获取轨道状态颜色
  Color _getTrackStatusColor(XhDanmuTrackStatus status) {
    switch (status) {
      case XhDanmuTrackStatus.idle:
        return Colors.green;
      case XhDanmuTrackStatus.normal:
        return Colors.orange;
      case XhDanmuTrackStatus.busy:
        return Colors.red;
    }
  }
}

/// XH弹幕控制面板（调试用）
class XhDanmuControlPanel extends StatelessWidget {
  final XhDanmuController controller;
  final List<Widget>? customButtons;
  final Color? backgroundColor;
  final BorderRadius? borderRadius;

  const XhDanmuControlPanel({
    super.key,
    required this.controller,
    this.customButtons,
    this.backgroundColor,
    this.borderRadius,
  });

  @override
  Widget build(BuildContext context) {
    return GetBuilder<XhDanmuController>(
      init: controller,
      builder: (ctrl) => Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: backgroundColor ?? Colors.black.withOpacity(0.8),
          borderRadius: borderRadius ?? BorderRadius.circular(12),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 基本控制按钮
            Wrap(
              spacing: 8,
              runSpacing: 8,
              alignment: WrapAlignment.center,
              children: [
                // 播放/暂停按钮
                ElevatedButton.icon(
                  onPressed: () {
                    if (ctrl.isPlaying) {
                      ctrl.pauseAnimation();
                    } else {
                      ctrl.startAnimation();
                    }
                  },
                  icon: Icon(
                    ctrl.isPlaying ? Icons.pause : Icons.play_arrow,
                    size: 16,
                  ),
                  label: Text(
                    ctrl.isPlaying ? '暂停' : '播放',
                    style: const TextStyle(fontSize: 12),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ctrl.isPlaying ? Colors.orange : Colors.green,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  ),
                ),

                // 清空按钮
                ElevatedButton.icon(
                  onPressed: ctrl.clearAllDanmu,
                  icon: const Icon(Icons.clear_all, size: 16),
                  label: const Text('清空', style: TextStyle(fontSize: 12)),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  ),
                ),

                // 测试按钮（已禁用 - 需要外部实现）
                ElevatedButton.icon(
                  onPressed: null, // 禁用，因为核心库不再提供具体实现
                  icon: const Icon(Icons.send, size: 16),
                  label: const Text('测试', style: TextStyle(fontSize: 12)),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  ),
                ),

                // 自定义按钮
                if (customButtons != null) ...customButtons!,
              ],
            ),

            const SizedBox(height: 12),

            // 简单状态指示器
            _buildSimpleStatus(ctrl),
          ],
        ),
      ),
    );
  }

  /// 构建简单状态指示器
  Widget _buildSimpleStatus(XhDanmuController controller) {
    final status = controller.getStatus();

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: Colors.black54,
        borderRadius: BorderRadius.circular(6),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Text(
            '活跃: ${status.totalActiveDanmu}',
            style: const TextStyle(color: Colors.white, fontSize: 12),
          ),
          Text(
            '队列: ${status.totalQueuedDanmu}',
            style: const TextStyle(color: Colors.white, fontSize: 12),
          ),
          Text(
            status.isPlaying ? "播放中" : "暂停",
            style: TextStyle(
              color: status.isPlaying ? Colors.green : Colors.orange,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }
}

/// 弹幕性能监控组件
class XhDanmuPerformanceMonitor extends StatelessWidget {
  final XhDanmuController controller;
  final Duration updateInterval;

  const XhDanmuPerformanceMonitor({
    super.key,
    required this.controller,
    this.updateInterval = const Duration(seconds: 1),
  });

  @override
  Widget build(BuildContext context) {
    return GetBuilder<XhDanmuController>(
      init: controller,
      builder: (ctrl) {
        final completionRate =
            ctrl.totalDanmuSent > 0 ? (ctrl.totalDanmuCompleted / ctrl.totalDanmuSent * 100) : 0.0;

        return Container(
          padding: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.black87,
            borderRadius: BorderRadius.circular(6),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                '性能监控',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                '发送: ${ctrl.totalDanmuSent}条',
                style: const TextStyle(color: Colors.white70, fontSize: 10),
              ),
              Text(
                '完成: ${ctrl.totalDanmuCompleted}条',
                style: const TextStyle(color: Colors.white70, fontSize: 10),
              ),
              Text(
                '完成率: ${completionRate.toStringAsFixed(1)}%',
                style: TextStyle(
                  color: completionRate > 95 ? Colors.green : Colors.orange,
                  fontSize: 10,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
